﻿using System.Diagnostics;
using System.Reflection;
using rpc_service.log;
using Microsoft.Extensions.Logging;
using rpc_service.external;
using ILogger = Microsoft.Extensions.Logging.ILogger;

namespace rpc_service.core.interceptor.impl;

public class RequestInterceptor : Interceptor
{
    private readonly ILogger _logger = Logger.GetLoggerFactory().CreateLogger("RequestInterceptor");
    private readonly Stopwatch _stopwatch = new Stopwatch();
    private string _requestId;
    public static UUIDApi GetUUIDApi;

    public RequestInterceptor() : base(999)
    {
        
    }

    public void PreInterceptor(IDictionary<string, object> parameter)
    {
        HttpClient httpClient = (parameter["client"] as HttpClient)!;
        
        if (httpClient.DefaultRequestHeaders.Contains("X-Request-ID"))
        {
            _requestId = httpClient.DefaultRequestHeaders.GetValues("X-Request-ID").First();
        }
        else
        {
            _requestId = GetUUIDApi.Get();
            httpClient.DefaultRequestHeaders.Add("X-Request-ID", _requestId);
        }
        
        _logger.LogInformation($"[{_requestId}] ==================== 请求开始 ====================");
        
        // 开始计时
        _stopwatch.Start();

        // 记录基本请求信息 
        _logger.LogInformation($"[{_requestId}] 开始HTTP请求");

        // 记录请求地址信息 
        _logger.LogInformation($"[{_requestId}] 请求url: {parameter["url"]}");
        _logger.LogInformation($"[{_requestId}] 请求参数: {parameter["data"]}");

        // 记录请求超时设置 
        _logger.LogInformation($"[{_requestId}] 请求超时设置: {httpClient.Timeout}");

        // 记录请求头信息 
        if (httpClient.DefaultRequestHeaders != null && httpClient.DefaultRequestHeaders.Any())
        {
            _logger.LogInformation($"[{_requestId}] 请求头信息:");
            foreach (var header in httpClient.DefaultRequestHeaders)
            {
                _logger.LogInformation($"[{_requestId}]  {header.Key}: {string.Join(", ", header.Value)}");
            }
        }
        else
        {
            _logger.LogInformation($"[{_requestId}] 请求头信息: 无");
        }
    }

    public void PostInterceptor(IDictionary<string, object> parameter, HttpResponseMessage response = null, Exception exception = null)
    {
        // 停止计时
        _stopwatch.Stop();

        // 计算请求用时
        var elapsedTime = _stopwatch.ElapsedMilliseconds;

        if (exception != null)
        {
            // 请求发生异常
            _logger.LogError($"[{_requestId}] HTTP请求异常，用时: {elapsedTime}ms, 异常信息: {exception.Message}");

            // 记录详细异常堆栈（可选）
            _logger.LogDebug($"[{_requestId}] 异常堆栈: {exception.StackTrace}");
        }
        else
        {
            // 记录响应状态
            string statusInfo = "未知状态";
            if (response != null)
            {
                statusInfo = $"{(int)response.StatusCode} {response.StatusCode}";

                // 记录响应头信息
                _logger.LogInformation($"[{_requestId}] 响应状态: {statusInfo}");

                if (response.Headers != null && response.Headers.Any())
                {
                    _logger.LogInformation($"[{_requestId}] 响应头信息:");
                    foreach (var header in response.Headers)
                    {
                        _logger.LogInformation($"[{_requestId}]   {header.Key}: {string.Join(", ", header.Value)}");
                    }
                }

                // 可以选择性地记录响应内容（对于大型响应，可能需要限制输出）
                // 这里省略了响应内容的记录，如果需要可以添加
            }

            // 请求结束语
            _logger.LogInformation($"[{_requestId}] HTTP请求完成，状态: {statusInfo}, 用时: {elapsedTime}ms");
        }

        // 添加结束语
        _logger.LogInformation($"[{_requestId}] ==================== 请求结束 ====================");
    }
}